import { useEffect, useMemo, useRef, useState } from 'react'
import type { CardPaperProps } from '../../CardPageType'
import './CardPaperStyle.sass'

function CardPaper (props: CardPaperProps) {
  // #region 变量声明
  const [ time, setTime ] = useState(7500)
  const timer = useRef<NodeJS.Timeout | string | number | undefined>(undefined)
  const first = useRef(false)
  // #endregion

  // #region 函数
  const finishedHandler = () => {
    // console.log(timer.current)
    clearInterval(timer.current)
    const score = props.state.list.reduce((res, item) =>  {
      return res + ((item.myResult && item.myResult === item.result) ? item.score : 0)
    }, 0)
    props.dispatch({ type: 'isFinished', value: true })
    alert('你的成绩为' + score + '分')
  }
  const countDown = useRef(() => {
    if (timer.current) clearInterval(timer.current)
    timer.current = setInterval(() => {
      setTime(prevTime => {
        if (prevTime === 1) {
          clearInterval(timer.current)
          finishedHandler()
        }
        return prevTime - 1
      })
    }, 1000)
  })

  const clickHandler = (index: number) => {
    // console.log(index)
    props.dispatch({ type: 'curClickIndex', value: index })
    // console.log(props.state)
  }

  // #endregion

  // #region Hooks
  const timeText = useMemo(() => {
    const h = Math.floor(time / 60 / 60)
    const m = Math.floor(time / 60 % 60)
    const s = Math.floor(time % 60)
    return String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0')
  }, [time])

  useEffect(() => {
    // console.log(111)
    if (first.current) {
      clearInterval(timer.current)
    } else {
      countDown.current()
      first.current = true
    }
  }, [])
  // #endregion

  return (
    <>
      <div className="card_paper">
        <header>
          <span>答题卡</span>
          <span className='time'>{ timeText }</span>
        </header>
        <main>
          <div className="head">
            <span>单选题</span>
            <span>共{ props.state.list.length }题</span>
          </div>
          <ul className="nos">
            {
              props.state.list.map((item, index) => (
                <li onClick={ () => clickHandler(index) } key={ index } className={ item.myResult ? 'finished' : '' }><span>{ index + 1 }</span></li>
              ))
            }
          </ul>
        </main>
        <footer>
          <button onClick={ finishedHandler }>交卷</button>
        </footer>
      </div>
    </>
  )
}

export default CardPaper
